<?php

namespace TpAmis\build;

use TpAmis\Renderers\BaseApi;
use TpAmis\Renderers\BaseRenderer;
use TpAmis\Renderers\Operation;
use TpAmis\Traits\BaseApiTrait;
use TpAmis\Traits\ButtonsTrait;
class TableBuilder extends BaseRenderer
{
    use BaseApiTrait;
    use ButtonsTrait;

    protected array $columns = [];
    protected object $amis;
    protected string $primaryKey = 'id';


    public function __construct()
    {
        $this->amis = amis()->CRUDTable();
        $this->HeaderButtons();

        $this->setApi($this->BaseApiPost('index'));
    }

    public static function amis()
    {
        return new self();
    }

    protected BaseApi $api;

    /**
     * @param BaseApi $api
     * @return $this
     */
    public function setApi(BaseApi $api): TableBuilder
    {
        $this->api = $api;
        return $this;
    }

    function setSearch($items = [])
    {
        foreach ($items as $item) {
            //后期增加数组构建搜索表单
            $this->amis = $this->amis->filter($item);
        }
    }

    public function fetch()
    {

        $this->amis = $this->amis->api($this->api);
        $this->baseHeaderToolBar();

        $this->amis = $this->amis->perPageField($this->perPageField)
            ->perPage($this->perPage)
            ->alwaysShowPagination()
            ->affixHeader(false)
            ->autoFillHeight(true)
            ->filterTogglable()
            ->filterDefaultVisible(false)
            ->quickSaveApi(adminUrl('quickEditedOne'))
            ->quickSaveItemApi(adminUrl('quickEditedOne'))
            ->bulkActions($this->bulkActions)
            ->perPageAvailable($this->perPageAvailable)
            ->footerToolbar($this->baseFooterToolBar)
            ->headerToolbar($this->baseHeaderToolBar)
            ->columns($this->builderColumn());
        return $this->amis;
    }

    private function builderColumn()
    {
        $columns = [];
        foreach ($this->columns as $column) {

            $Column = $this->CheckType($column['type'], $column);

            foreach ($column['options'] as $key => $value) {
                $Column->set($key, $value);
            }
            $columns[] = $Column;
        }

        return $columns;
    }

    /**
     * @param string $name
     * @param string $label
     * @param string $type
     * @param string|array $default
     * @param array $options
     * @return $this
     */
    public function addColumn(string $name = '', string $label = '', string $type = 'text', $remark = '', $default = '', array $options = []): TableBuilder
    {

        $type = strtolower($type);

        $column = [
            'name' => $name,
            'label' => $label,
            'type' => $type,
            'remark' => $remark,
            'default' => $default,
            'options' => $options,
        ];
        $args = array_slice(func_get_args(), 5);
        $args = array_merge($column, $args);

        $this->columns[] = $args;
        return $this;
    }

    private function CheckType($type, $args)
    {
        $Column = amis()->TableColumn($args['name'], $args['label'])->remark($args['remark']);

        switch ($type) {
            case 'status':

                if (is_array($args['default'])) {
                    $options = [];
                    foreach ($args['default'] as $value => $name) {
                        $options[] = ['label' => $name, 'value' => $value];
                    }
                    $Column->type('mapping')->map($options);
                } else {
                    $Column->type('mapping')->map($args['default']);
                }
                break;
            case 'select':

                break;
            case 'btn':
                return $this->rowActions();
                break;
            default:
                $Column->type($type);
        }

        return $Column;
    }

    /**
     * @param array $columns
     * @return $this
     */
    public function addColumns(array $columns = []): TableBuilder
    {
        foreach ($columns as $options) {
            call_user_func_array([$this, 'addColumn'], $options);
        }
        return $this;
    }


    protected array $baseHeaderToolBar = [];

    function setHeader($Actions): TableBuilder
    {
        $this->baseHeaderToolBar[] = $Actions;
        return $this;
    }


    /**
     * 基础顶部工具栏
     */
    private function baseHeaderToolBar(): void
    {
        $this->baseHeaderToolBar[] = 'bulkActions';
        $this->baseHeaderToolBar[] = amis('export-excel')->align('right');
        $this->baseHeaderToolBar[] = amis('reload')->align('right');
        $this->baseHeaderToolBar[] = amis('filter-toggler')->align('right');
    }


    protected array $baseFooterToolBar = ['switch-per-page', 'statistics', 'pagination'];

    private function setFooter($Actions)
    {
        $this->baseFooterToolBar[] = $Actions;
    }

    protected array $perPageAvailable = [10, 15, 20, 25, 50, 100];
    protected int $perPage = 10;
    protected string $perPageField = 'list_rows';

    protected array $bulkActions = [];

    public function HeaderButtons()
    {
        $this->amis->bulkActions($this->bulkActions);

    }

    public function setHeaderButtons($Actions): TableBuilder
    {
        $this->bulkActions[] = $Actions;
        return $this;
    }

    protected array $rowActions = [];

    /**
     * 操作列
     * @return Operation
     */
    protected function rowActions(): Operation
    {
        return amis()->Operation()->label('操作')->buttons($this->rowActions);
    }

    /**
     * 批量添加右侧按钮
     * @param array $buttons
     * @return $this
     */
    public function addRightButtons(array $buttons = []): TableBuilder
    {
        if (!empty($buttons)) {
            $buttons = is_array($buttons) ? $buttons : explode(',', $buttons);
            foreach ($buttons as $key => $value) {
                if (is_numeric($key)) {
                    $this->addRightButton($value);
                } else {

                    $this->addRightButton($key, ...$value);
                }
            }
        }
        return $this;
    }

    public function addRightButton($type = '', ...$args): TableBuilder
    {
        if (is_array($type)) {
            $args = $type;
            $type = $type['type'];
        }

        switch ($type) {
            // 编辑按钮
            case 'edit':
                $this->rowActions[] = $this->rowEditorButton(...$args);
                break;
            // 编辑按钮
            case 'status':
                $this->rowActions[] = $this->rowStatusButton(...$args);
                break;

            // 启用按钮
            case 'enable':
                $this->rowActions[] = $this->rowEnableButton(...$args);
                break;

            // 禁用按钮
            case 'disable':
                $this->rowActions[] = $this->rowDisableButton(...$args);
                break;

            // 删除按钮(不可恢复)
            case 'delete':
                $this->rowActions[] = $this->rowDeleteButton(...$args);
                break;
            // 自定义按钮
            case 'custom':
            default:
                $this->rowActions[] = $this->customButton(...$args);
                break;
        }
        return $this;
    }

    /**
     * 批量添加右侧按钮
     * @param string|array $buttons
     * @return $this
     */
    public function addTopButtons($buttons = []): TableBuilder
    {
        if (!empty($buttons)) {
            $buttons = is_array($buttons) ? $buttons : explode(',', $buttons);

            foreach ($buttons as $key => $value) {
                if (is_numeric($key)) {
                    $this->addTopButton($value);
                } else {

                    $this->addTopButton($key, ...$value);
                }
            }
        }
        return $this;
    }

    public function addTopButton($type = '', ...$args): TableBuilder
    {
        if (is_array($type)) {
            $args = $type;
            $type = $type['type'];
        }

        switch ($type) {
            // 编辑按钮
            case 'create':
                $this->baseHeaderToolBar[] = $this->createButton(...$args);
                break;
            // 编辑按钮
            case 'status':
                $this->bulkActions[] = $this->rowStatusButton(...$args)->level('primary');
                break;

            // 启用按钮
            case 'enable':
                $this->bulkActions[] = $this->rowEnableButton(...$args)->level('primary');
                break;

            // 禁用按钮
            case 'disable':
                $this->bulkActions[] = $this->rowDisableButton(...$args)->level('primary');
                break;

            // 删除按钮(不可恢复)
            case 'delete':
                $this->bulkActions[] = $this->bulkDeleteButton(...$args);
                break;
            // 自定义按钮
            case 'custom':
            default:
                $this->bulkActions[] = $this->customButton(...$args);
                break;
        }
        return $this;
    }

    public function excel()
    {
        amis()->IFrame()->src('')->events([
            'push_data' => [
                'actions' => [
                    [
                        "actionType" => "dialog",
                        "dialog" => [
                            "title" => "弹框",
                            "body" => 'iframe 传给 amis 的 id 是：${iframeId}' // 在弹框中渲染`"iframe 传给 amis 的 id 是：${iframeId}"`这段模板，即111

                        ]
                    ]
                ],
            ]
        ]);
    }

    public function __call($name, $arguments)
    {
        if (strpos($name, 'set') !== false) {
            $name = str_replace('set', '', $name);

            $this->amis = $this->amis->$name(...$arguments);
        }


        return $this;
    }
}
